// src/stores/deepseek.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { deepseekApi } from './deepAxios'
import { findMergeRequestChanges } from './index'


export const useDeepSeekStore = defineStore('deepseek', () => {
  const reviewResults = ref([])
  const config = ref({
    apiKey: 'sk-jammjrdzakqbpehfkphffllpxxwsykgwxqvovhhgrjdoyqyb'
  })

  const isConfigured = computed(() => {
    return !!config.value.apiKey
  })

  const saveConfig = (apiKey) => {
    config.value.apiKey = apiKey
    localStorage.setItem('deepseek_api_key', apiKey)
    deepseekApi.updateConfig(apiKey)
  }

  const analyzeCode = async (code, context) => {
    // if (!isConfigured.value) {
    //   throw new Error('请先配置DeepSeek API密钥')
    // }

    try {
      const response = await deepseekApi.post('/chat/completions', {
        model: 'deepseek-ai/DeepSeek-V3',
        messages: [
          {
            role: 'system',
            content: '你是一个专业的代码审查助手，提供详细、结构化的中文审查报告。包括总体评价、问题分类、改进建议和评分。'
          },
          {
            role: 'user',
            content: generatePrompt(code, context)
          }
        ],
        temperature: 0.1,
        max_tokens: 2000
      })

      return response.data.choices[0].message.content
    } catch (error) {
      throw new Error('DeepSeek分析失败: ' + error.message)
    }
  }

  const reviewMergeRequest = async (project, mr) => {
    const changes = await findMergeRequestChanges(project.id, mr.iid)
    reviewResults.value = []

    for (const change of changes.changes) {
      if (shouldReviewFile(change.new_path)) {
        const review = await analyzeCode(change.diff, {
          filePath: change.new_path,
          mrTitle: mr.title,
          projectName: project.name
        })

        if (review) {
          reviewResults.value.push({
            filePath: change.new_path,
            diff: change.diff,
            review: review,
            score: extractScore(review)
          })
        }
      }
    }
  }

  const clearResults = () => {
    reviewResults.value = []
  }

  // 辅助函数
  const generatePrompt = (code, context) => {
    return `请对以下代码变更进行专业审查：

文件: ${context.filePath}
项目: ${context.projectName}
合并请求: ${context.mrTitle}

代码变更:
\`\`\`diff
${code.substring(0, 3000)}
\`\`\`

请提供详细的中文审查报告，包括：
1. 总体评价和评分(1-10分)
2. 严重问题（安全、性能等）
3. 一般问题（代码质量、风格等）
4. 改进建议
5. 最佳实践建议`
  }

  const shouldReviewFile = (filePath) => {
    const ignorePatterns = [
      /\.md$/i, /\.json$/i, /\.yml$/i, /\.yaml$/i,
      /package-lock\.json$/i, /yarn\.lock$/i,
      /\.gitignore$/i, /\.env/, /dist\//, /node_modules\//
    ]
    return !ignorePatterns.some(pattern => pattern.test(filePath))
  }

  const extractScore = (review) => {
    const match = review.match(/评分[：:]\s*(\d+(?:\.\d+)?)\/10/)
    return match ? parseFloat(match[1]) : 7
  }

  return {
    reviewResults,
    config,
    isConfigured,
    saveConfig,
    analyzeCode,
    reviewMergeRequest,
    clearResults
  }
})